import React, { Component } from 'react'

class DeviceLog extends Component {
  constructor(props) {
    super(props)

    this.state = {
      logs: []
    }
  }

  componentDidMount() {
    let ws = new WebSocket(
      'ws://localhost:3000/ws/' +
        document.location.href.substr(
          '/links/'.length + document.location.href.indexOf('/links/')
        )
    )
    ws.onopen = function() {
      // Web Socket 已连接上，使用 send() 方法发送数据
    }

    ws.onmessage = evt => {
      var received_msg = evt.data
      this.setState({
        logs: [...this.state.logs, received_msg]
      })
    }

    ws.onclose = function() {
      // 关闭 websocket
    }
  }
  render() {
    const { logs } = this.state
    return (
      <code
        style={{
          backgroundColor: 'black',
          padding: 10,margin: 10,
          height: '100%',
          color: 'white',
          wordWrap: 'break-word',
          wordBreak: 'break-word',
          overflow: 'hidden'
        }}
      >
        {logs.map((l, index) => {
          return (
            <React.Fragment key={index}>
              {l}
              <br />
            </React.Fragment>
          )
        })}
      </code>
    )
  }
}

export default DeviceLog
